<?php

class Admin_OpenId_ServerConfirmView extends BlogAdminBaseView
{
	public function executeLhtml(AgaviRequestDataHolder $rd)
	{
        $openid_server = $this->getAttribute('openid_server');
        $openid_request = $this->getAttribute('openid_request');
        $params = $rd->getParameters();
        $model = $this->getContext()->getModel('OpenId', 'Admin');
        
        $url = $openid_request->trust_root;
        $return_to = $openid_request->return_to;
        // check that server is in the trusted sites list
        
        //var_dump($openid_request->idSelect());
        if (isset($params['confirm_login']) || $model->isSiteTrusted($url)) {
            // i.e site is trusted or directly confirmed, redirect to url
            if (isset($params['add_to_trusted'])) {
                // add to trusted sites
                $model->addSiteToTrusted($url);
            }
            $req_url = $openid_request->identity;
            $openid_response = $openid_request->answer(true, null, $req_url);

            // TODO: Enable later
            // require_once 'Auth/OpenID/SReg.php';
            //$sreg_data = array(
            //    'fullname' => 'Example User',
            //    );
            // $sreg_request = Auth_OpenID_SRegRequest::fromOpenIDRequest($openid_request);
            // $sreg_response = Auth_OpenID_SRegResponse::extractResponse($sreg_request, $sreg_data);
            // $sreg_response->toMessage($openid_response->fields);
            
            $web_response = $openid_server->encodeResponse($openid_response);
            $agavi_response = $this->getResponse();
            
            foreach ($web_response->headers as $k => $v) {
                $agavi_response->setHttpHeader($k, $v);
                //var_dump($v);
            }
            $agavi_response->setHttpHeader('Connection', 'close');

            return $web_response->body;
            //var_dump($openid_request->trust_root);
		    //$this->getResponse()->setRedirect($openid_request->return_to);
		    //return;
        }
		//$this->setupHtml($rd);

		//$this->setAttribute('_title', 'OpenId.Server');
		
        $ro = $this->getContext()->getRouting();
        
        // construct new params
        $new_params = array();
        foreach ($params as $k=>$v) {
            $k = preg_replace('/^openid_/', 'openid.', $k);
            $k = preg_replace('/^openid\\.sreg_/', 'openid.sreg.', $k);
            $new_params[$k] = $v;
        }
        //var_dump($params);
        // display confirmation
        $this->setupHtml($rd, 'compact');
        $this->setAttribute('submit_route', $ro->gen('openid.confirm', array(), array('relative'=>FALSE)));
        $this->setAttribute('parameters', $new_params);
        $this->setAttribute('remote_url', $url);
        $this->setAttribute('current_openid', $ro->gen('/', array(), array('relative'=>FALSE)));

        return false;
        //return $confirmation_action_url;
	}
}

?>
